# from django.shortcuts import render
# from rest_framework.views import APIView
# from luffyapi.utils.response import APIResponse
# from luffyapi.utils.logger import log
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import GenericViewSet
from . import models
from . import serializer
from django.conf import settings
from django.core.cache import cache
from rest_framework.response import Response

# class BannerView(GenericAPIView, ListModelMixin):
# 继承GenericAPIView，路由的写法：path('banner/', views.BannerView.as_view())


class BannerView(GenericViewSet, ListModelMixin):
    # 可以限制：无论有多少待展示的数据，最多就展示3条，将3配置到配置文件中（有的公司可能会配置到数据库中）
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True)\
                   .order_by('orders')[:settings.BANNER_COUNTER]
    # filter(没有标为已删的和可以显示出来的).按照'显示顺序'字段排序.拿到前BANNER_COUNTER条数据
    # BANNER_COUNTER在const.py中，const.py被引用到了配置文件dev.py

    serializer_class = serializer.BannerModelSerializer
    """
    继承GenericViewSet，路由的写法：
    from django.urls import path, include
    from . import views
    from rest_framework.routers import SimpleRouter


    router = SimpleRouter()
    router.register('banner', views.BannerView, 'banner')
    urlpatterns = [
        path('', include(router.urls))  # 自动生成路由
    ]
    """

    def list(self, request, *args, **kwargs):
        """重写父类的list方法，从缓存中取轮播图的数据"""
        # 第一步，先去缓存中拿数据
        banner_list = cache.get('banner_list')
        # 缓存中没有的情况下
        if not banner_list:
            # 用父类的方法去数据库拿
            response = super().list(request, *args, **kwargs)
            # 加到缓存
            cache.set('banner_list', response.data, 60*60*24)  # 存储时，key值最好复杂些，避免重复
            print('走数据库了')
            return response  # 将从数据库拿到的数据返回
        # 如果第一步中取到了数据，这里直接返回
        return Response(data=banner_list)










